<template>
  <el-select
    v-model="tableId"
    :placeholder="placeholder"
    @change="refresh"
  >
    <el-option v-for="i in tables" :key="i.Id" :label="i.TableLabel" :value="i.Id" />
  </el-select>
</template>

<script>

import { GetTable } from '@/customForm/api/form'
export default {
  components: {
  },
  props: {
    formId: {
      type: String,
      default: null
    },
    value: {
      type: String,
      default: null
    },
    placeholder: {
      type: String,
      default: '选择数据表'
    },
    filter: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      tables: [],
      tableId: null
    }
  },
  watch: {
    formId: {
      handler(val) {
        if (val) {
          this.initTable()
        } else if (this.tableId != null) {
          this.tableId = null
          this.tables = []
          this.refresh()
        } else {
          this.tables = []
        }
      },
      immediate: true
    },
    value: {
      handler(val) {
        this.tableId = val
      },
      immediate: true
    },
    filter: {
      handler(val) {
        if (this.formId != null) {
          this.initTable()
        }
      },
      immediate: false
    }
  },
  mounted() { },
  methods: {
    async initTable() {
      const list = await GetTable(this.formId)
      if (this.filter != null) {
        this.tables = list.filter(c => this.filter(c))
      } else {
        this.tables = list
      }
    },
    refresh() {
      this.$emit('input', this.tableId)
      this.$emit('change', this.tableId)
    }
  }
}
</script>
